package com.example.internalstoragedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 文件名好像不能含路径
        save("test.txt", "数据\n测试");
        String content = read("test.txt");
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    private void save(String fileName, String content) {

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String read(String fileName) {
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = openFileInput(fileName);
            // 创建缓冲区
            byte[] buffer = new byte[fileInputStream.available()];
            // 一次读完
            fileInputStream.read(buffer);
            // 转成String返回
            return new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}